﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Collections.Generic
{
    /// <summary>
    /// IEnumerable的接口扩展
    /// </summary>
    public static class IEnumerableExtension
    {
        /// <summary>
        /// 找到第一个匹配的元素
        /// </summary>
        public static T Find<T>(this IEnumerable<T> data, Predicate<T> match)
        {
            T result = default(T);
            foreach (T item in data)
            {
                if (match(item))
                {
                    result = item;
                    break;
                }
            }
            return result;
        }

        /// <summary>
        /// 找到匹配的元素集合
        /// </summary>
        public static IEnumerable<T> FindAll<T>(this IEnumerable<T> data, Predicate<T> match)
        {
            IList<T> result = new List<T>();
            foreach (T item in data)
            {
                if (match(item)) result.Add(item);
            }
            return result;
        }

        /// <summary>
        /// 枚举处理IEnumerable的内容
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <param name="action"></param>
        public static void ForEach<T>(this IEnumerable<T> data, Action<T> action)
        {
            foreach (T item in data)
            {
                action(item);
            }
        }
    }
}
